package com.gzz.orchid.common.core.tuple;

import com.gzz.orchid.common.core.exception.ValidationException;
import com.gzz.orchid.common.core.util.I18nUtil;
import lombok.Value;

import java.math.BigDecimal;
import java.util.Currency;
import java.util.Objects;

/**
 * 金钱
 *
 * @author higmd
 */
@Value
public class Money {
    BigDecimal value;
    Currency currency;
    // 构造函数
    public Money(BigDecimal amount, Currency currency) {
        if (Objects.isNull(amount)) {
            throw new ValidationException(I18nUtil.ofMessage("金额值不能为空"));
        }
        this.value = amount;
        if (Objects.isNull(currency)) {
            currency = Currency.getInstance("CNY");
        }
        this.currency = currency;
    }

    public static Money ofZero() {
        return new Money(BigDecimal.ZERO, null);
    }

    /**
     * 检查金额类型是否相同
     */
    private void checkSameCurrency(Money amt) throws IllegalArgumentException {
        if (!amt.getCurrency().equals(this.getCurrency())) {
            throw new IllegalArgumentException(I18nUtil.ofMessage("货币类型必须相同"));
        }
    }

    /**
     * 增加金额
     */
    public Money add(Money amt) {
        this.checkSameCurrency(amt);
        return new Money(this.value.add(amt.getValue()), this.currency);
    }

    /**
     * 减少金额
     */
    public Money subtract(Money amt) throws IllegalArgumentException {
        this.checkSameCurrency(amt);
        return new Money(this.value.subtract(amt.getValue()), this.currency);
    }

    /**
     * 同种货币比较
     */
    public boolean compare(Money amt) throws IllegalArgumentException {
        this.checkSameCurrency(amt);
        return this.value.compareTo(amt.getValue()) <= -1;
    }
}
